# coding=utf-8

# 支付宝支付监控平台

from bs4 import BeautifulSoup as bs
from requests.packages.urllib3 import connectionpool
import requests
import time
import logging

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    'Cookie': 'JSESSIONID=GZ00R9ctX4hUXeGMTASU6pgnmEgG1NshenghuoGZ00RZ13; cna=VnAcEPanOAwCAS0/e+I5ICb1; l=Av//gQt/Q4AjC-10AW1cxsujD9mJ1lOG; isg=AqGhnHWvUuiBAf4cXVa8bxQvsGuQPhVAFZw5xQN2r6gHasA8S5xXEp7quimW; NEW_ALIPAY_TIP=1; unicard1.vm="K1iSL1gn5tJnKx5epbBmbw=="; session.cookieNameId=ALIPAYJSESSIONID; ALIPAYBUMNGJSESSIONID=GZ00wMl7iFNmJWYaGEkISjkZpl3LsAmobilecodecGZ00; JSESSIONID=DC77FCB0FAA170D2E8998875E7CEEFA8; mobileSendTime=-1; credibleMobileSendTime=-1; ctuMobileSendTime=-1; riskMobileBankSendTime=-1; riskMobileAccoutSendTime=-1; riskMobileCreditSendTime=-1; riskCredibleMobileSendTime=-1; riskOriginalAccountMobileSendTime=-1; ctoken=Sf-R-SG0T2eQRB-M; LoginForm=alipay_login_auth; alipay=K1iSL1gn5tJnKx5epbBmbxlkIqVN+VBboBYOHhnYGhMkQzo9; CLUB_ALIPAY_COM=2088102963584721; iw.userid="K1iSL1gn5tJnKx5epbBmbw=="; ali_apache_tracktmp="uid=2088102963584721"; zone=RZ13A; ALIPAYJSESSIONID=RZ13GWOODuYMWPSHyy2Xqob0BeGXWlauthRZ13GZ00; spanner=QOuHk7Z3/0x1LjfjizZbnqALQAHjVpVF4EJoL7C0n0A=',
}

api = 'http://localhost:5000/v1/api'
key = 'gQy/aipUqAA4pm6HoJNW5w=='

url = 'https://lab.alipay.com/consume/record/items.htm'
logging.basicConfig(filename='/tmp/alipay.log',
                    level=logging.INFO,
                    format='[%(asctime)s %(levelname)s] %(message)s',
                    datefmt='%Y%m%d %H:%M:%S')
connectionpool.log.setLevel(logging.WARNING)


def get_payment_id(soup):
    payment_id = []
    for i in soup.select('.consumeBizNo'):
        payment_id.append(i.string.strip())
    return payment_id


def get_time(soup):
    t = []
    time_format = '%Y-%m-%d %H:%M:%S'
    for i in soup.select(".time"):
        t.append(int(time.mktime(time.strptime(i.string.strip(), time_format))))
    return t


def get_name(soup):
    name = []
    for i in soup.select('.emoji-li'):
        for ii in i.stripped_strings:
            name.append(ii)
    return name


def get_amount(soup):
    amount = []
    for i in soup.select('.amount.income'):
        amount.append(i.string)
    return amount


def post_data(payment_id, time, name, amount):
    data = {
        'key': key,
        'ddh': payment_id,
        'time': time,
        'name': name,
        'amount': amount,
    }

    try:
        requests.post(api, data=data, timeout=5)
    except StandardError as e:
        logging.warning('Timeout, retrying')
        post_data(payment_id, time, name, amount)
    logging.info('%s--%s--%s--%s' % (payment_id, time, name, amount))


def main():
    posted = []

    while True:
        if len(posted) > 1000:
            posted = []
        try:
            req = requests.get(url, headers=headers)
        except StandardError as e:
            logging.warning('connect to alipay failed')
            continue

        if req.url.startswith('https://auth.alipay.com/'):
            logging.critical('Authentication failed!')
            import sys

            sys.exit(0)

        html = req.text
        html = html.encode('gbk')
        soup = bs(html, 'lxml')
        # for i in soup.select('.amount.outlay'):
        #     i.parent.decompose()
        #
        # for i in soup.select('.subTransCodeValue'):
        #     i.decompose()

        payment_id = get_payment_id(soup)
        t = get_time(soup)
        name = get_name(soup)
        amount = get_amount(soup)
        length = len(payment_id)

        for i in range(length):
            if not name[i].startswith(u'付款-'):
                continue

            if payment_id[i] not in posted:
                post_data(payment_id[i],
                          t[i],
                          name[i].split('-')[1],
                          amount[i])
                posted.append(payment_id[i])

        time.sleep(5)
        print 'next start'


if __name__ == '__main__':
    main()
